package de.herzog.bbp.model.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractDAO {

	private static final Logger LOG = LoggerFactory.getLogger(AbstractDAO.class);

	private static Session session;
	private static SessionFactory sessionFactory;

	protected static Session getSession() throws HibernateException {
		if (session == null) {
			if (sessionFactory == null) {
				sessionFactory = new Configuration().configure().buildSessionFactory();
			}
			session = sessionFactory.openSession();
		}
		return session;
	}

	public static void persist(Object object) {
		Session session = getSession();
		session.beginTransaction();
		session.persist(object);
		session.getTransaction().commit();
		LOG.debug("Persisted " + object);
	}

	public static Long count(Class<?> clazz) {
		Criteria criteria = getSession().createCriteria(clazz);
		return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
	}

	public static List<Object[]> count(Class<?> clazz, String... groupProperties) {
		Criteria criteria = getSession().createCriteria(clazz);
		ProjectionList projectionList = Projections.projectionList();
		for (String groupProperty : groupProperties) {
			projectionList.add(Projections.groupProperty(groupProperty));
		}
		projectionList.add(Projections.rowCount());
		criteria.setProjection(projectionList);
		@SuppressWarnings("unchecked")
		List<Object[]> list = criteria.list();
		return list;
	}
}
